//
//  WBPicCollectionViewController.swift
//  SinaWeibo
//
//  Created by zhuangqianwei on 16/11/22.
//  Copyright © 2016年 zhuangqianwei. All rights reserved.
//

import UIKit

let colCount: CGFloat = 3
let selectorMargin: CGFloat = 4
//最大数量
private let maxCount = 9
let selectorCellWidth = (ScreenWidth - (colCount + 1) * selectorMargin) / colCount
private let reuseIdentifier = "Cell"

class WBPicCollectionViewController: UICollectionViewController {

    //定义图片数组，存储用户选择的图片
    lazy var selectedImages: [UIImage] = [UIImage]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        self.collectionView!.register(PictureSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        
        
    }

      // MARK: UICollectionViewDataSource

   
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        let delta = self.selectedImages.count == maxCount ? 0 : 1
        return self.selectedImages.count + delta
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PictureSelectorCell
         cell.backgroundColor = randomColor()
        //设置代理
        cell.delegate = self
        //设置数据
        //判断如果是加载的最后一条数据就特殊处理
        if indexPath.item == self.selectedImages.count {
            //给最后一个cell的数据赋值
            cell.image = nil
        }else{
            cell.image = self.selectedImages[indexPath.item]
        }
        return cell
    }

}
 //MARK: 遵守cell的协议 实现协议方法
    extension WBPicCollectionViewController: PicctureSelectorCellDelegate {
        func userWillChosePic(cell: PictureSelectorCell?) {
            //modal图片选择器
            let picker = UIImagePickerController()
            //是否允许编辑
            picker.allowsEditing = true
            //设置picker代理
            picker.delegate = self
            //modal
            self.present(picker, animated: true, completion: nil)
        }
        
        func userWillRemovePic(cell: PictureSelectorCell) {
            //根据被点击的cell  通过collectionView 获取对应的indexPath
            guard let indexPath = collectionView?.indexPath(for: cell) else {
                
                return
            }
            //在数据删除 对应 的图片
            self.selectedImages.remove(at: indexPath.item)
            //刷新数据
            self.collectionView?.reloadData()
        }
        
}

   //遵守图片选择器代理协议
extension WBPicCollectionViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
//实现协议方法  一旦实现协议方法 小程序员需要手动dismiss
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        //获取选择图片
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        //将图片添加到数组中
        self.selectedImages.append(image.scaleImage(width: ScreenWidth))
        //dismiss控制器
        dismiss(animated: true, completion: {
            //刷新collectionview
            self.collectionView?.reloadData()
        })
    }
    
    
}

//定义协议
@objc protocol PicctureSelectorCellDelegate: NSObjectProtocol{
    
    //定义可选的协议方法
    //添加图片
    @objc optional func userWillChosePic(cell: PictureSelectorCell)
    
    //删除图片
    @objc optional func userWillRemovePic(cell: PictureSelectorCell)
    
    
}



    //自定义cell
    class PictureSelectorCell: UICollectionViewCell {
        //cell的事件跑出 不建议使用闭包 ，使用代理
        var addClosuer: (() -> ())?
        var removeClosure: (() -> ())?
        //使用weak修饰
        weak var delegate: PicctureSelectorCellDelegate?
        var image: UIImage? {
            
            didSet{
                
                //设置添加按钮的image
                addBtn.setImage(image, for: .normal)
                
                removeBtn.isHidden = image == nil
            }
        }

        @objc private func addBtnDidClick() {
            //跳转到选择图片等控制器  cell 中不能完成跳转
            //调用代理方法
            if image != nil {
                return
            }
            delegate?.userWillChosePic?(cell: self)
    }
        
        @objc private func removeBtnDidClick() {
            //removeClosure?()
            delegate?.userWillRemovePic?(cell: self)
        }

        //重写init方法
        override init(frame: CGRect) {
            super.init(frame: frame)
            setupUI()
        }
        
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }

        
        //设置UI
        private func setupUI() {
            
        self.contentView.addSubview(addBtn)
        self.contentView.addSubview(removeBtn)
        
        //设置约束
        addBtn.snp.makeConstraints { (make) in
            make.edges.equalTo(self)
        }
        
        removeBtn.snp.makeConstraints { (make) in
            make.right.top.equalTo(self.contentView)
        }
        
        //监听按钮点击事件
        addBtn.addTarget(self, action: #selector(addBtnDidClick), for: .touchUpInside)
        removeBtn.addTarget(self, action: #selector(removeBtnDidClick), for: .touchUpInside)
        
            
            
        }
        

    //懒加载视图
    lazy var addBtn: UIButton = {
    let btn = UIButton()
    //设置图片
    btn.setBackgroundImage(#imageLiteral(resourceName: "compose_pic_add"), for: .normal)
    btn.imageView?.contentMode = .scaleAspectFill
        return btn
}()
        
    lazy var removeBtn: UIButton = {
       let btn = UIButton()
       btn.setBackgroundImage(#imageLiteral(resourceName: "compose_photo_close"), for: .normal)
        return btn
    }()
}

